package com.dotflat.check.controller;

import com.alibaba.fastjson.JSON;

import com.dotflat.check.domain.CheckCard;
import com.dotflat.check.domain.Checker;
import com.dotflat.check.po.CheckerPO;
import com.dotflat.check.po.tianbo.TianBoApiResponse;
import com.dotflat.check.po.tianbo.pojo.PersonInfo;
import com.dotflat.check.po.tianbo.req.TianBoCaptureData;
import com.dotflat.check.po.tianbo.req.TianBoDeviceInfo;

import com.dotflat.check.po.tianbo.req.TianBoSyncPerson;
import com.dotflat.check.po.tianbo.rsp.TianBoLoginResponse;
import com.dotflat.check.po.tianbo.rsp.TianBoMqInfo;
import com.dotflat.check.po.tianbo.rsp.TianBoSyncPersonResponse;
import com.dotflat.check.service.CCheckerService;
import com.dotflat.check.service.CheckerService;
import com.dotflat.check.service.TianBoMqttService;
import com.dotflat.util.excelUtil.StringUtils;
import com.matt.commons.model.StatusResponse;
import com.matt.domain.Children;
import com.matt.foundation.utils.MapConvertUtil;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.service.ChildrenService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/iot/tianbo")
@Slf4j
@Api(tags = "考勤机 - 天波考勤机")
public class TianBoCheckerController {

    @Value("${iot.checker.tianbo.mqtt.host}")
    private String mqtt_host;

    @Value("${iot.checker.tianbo.mqtt.port}")
    private int mqtt_port;

    @Value("${iot.checker.tianbo.mqtt.topicprefix}")
    private String mqtt_topic_prefix;

    @Value("${iot.checker.tianbo.mqtt.account}")
    private String mqtt_account;

    @Value("${iot.checker.tianbo.mqtt.password}")
    private String mqtt_password;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private CheckerService checkerService;

    @Autowired
    private CCheckerService cCheckerService;

    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @ApiOperation(value = "设备登录")
    @PostMapping("/device/login")
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = CheckerPO.class),
    })
    public TianBoApiResponse deviceLogin(@RequestBody TianBoDeviceInfo deviceInfo) {

        log.info(JSON.toJSONString(deviceInfo));

        TianBoLoginResponse response = new TianBoLoginResponse();

        response.setToken(deviceInfo.getDevSno());
        response.setDev_sno(deviceInfo.getDevSno());
        response.setMsg("登录成功");

        TianBoMqInfo mqInfo = new TianBoMqInfo();
        mqInfo.setHost(mqtt_host);
        mqInfo.setPort(mqtt_port);
        mqInfo.setLogin(mqtt_account);
        mqInfo.setPassword(mqtt_password);

        String mqttTopic = mqtt_topic_prefix + "_" + deviceInfo.getDevSno();
        log.info("response for mqtt_topic " + mqttTopic);
        mqInfo.setTopic(mqttTopic);

        response.setMqinfo(mqInfo);

        return response;
    }

    @ApiOperation(value = "核验记录上传")
    @PostMapping("/record/upload/online")
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = CheckerPO.class),
    })
    public TianBoApiResponse recordUploadOnline(@RequestBody TianBoCaptureData captureReq) {
        log.info("RECORD UPLOAD ONLINE:::\n" +
                JSON.toJSONString(captureReq, true));

        log.info("设备上传的person_id：" + captureReq.getPerson_id()); // 新增此日志
        String childrenId = captureReq.getPerson_id();
        String devSno = captureReq.getDev_sno();
        String imageBase64 = captureReq.getCapture_img();
        String captureTimestamp = captureReq.getCapture_time();
        double personTemperature = captureReq.getPerson_temperature();



        if (StringUtils.isAnyBlank(childrenId, devSno, imageBase64, captureTimestamp)){
            return TianBoApiResponse.emptySuccess("错误的提交数据");
        }

//        Children byId = childrenService.getById(childrenId);
//        String areaId="";
//        if (byId!=null){
//            areaId = byId.getAreaId();
//        }
//        Checker checker = checkerService.getByDevSno1(devSno,areaId);
        Checker checker = checkerService.getByDevSno(devSno);

        if (checker == null){
            return TianBoApiResponse.emptySuccess("未配置的考勤机");
        }

        Date checkTime = new Date(Long.parseLong(captureTimestamp));
        cCheckerService.checkinChildren(checker, childrenId, imageBase64, checkTime,personTemperature);

        return TianBoApiResponse.emptySuccess("提交成功");
    }

    @ApiOperation(value = "总回调接口")
    @PostMapping("/device/notify")
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = CheckerPO.class),
    })
    public TianBoApiResponse deviceNotify(@RequestBody Map notifyContent) {
        log.info("TIANBO NOTIFY:::\n" +
        JSON.toJSONString(notifyContent, true));

        return TianBoApiResponse.emptySuccess("回调成功");

    }

    @ApiOperation(value = "同步所有用户数据")
    @PostMapping("/device/sync_person")
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = CheckerPO.class),
    })
    public TianBoApiResponse syncPerson(@RequestBody TianBoSyncPerson syncReq) {

        log.info("SYNC PERSON REQUEST:::\n" +
                JSON.toJSONString(syncReq, true));

//        Map params = (Map) syncReqMap.get("path_params");

        if (syncReq.getPath_params() == null){
            return TianBoApiResponse.emptySuccess("请求结构错误");
        }


        List<String> personList = (List<String>) syncReq.getPath_params().getPerson_list();
        log.info("上传的人============"+JSON.toJSONString(personList, true));

        if (personList == null||StringUtils.isEmpty(personList)|| personList.isEmpty()){
            return TianBoApiResponse.emptySuccess("请求结构错误!");
        }

        String devSno = syncReq.getDev_sno();

        //获取宝宝id
//        String childId = personList.get(0);
//        log.info("宝宝id============"+childId);
//        Children byId = childrenService.getById(childId);
//        String areaId="";
//        if (byId!=null){
//            areaId = byId.getAreaId();
//        }
//        Checker checker = checkerService.getByDevSno1(devSno,areaId);
        //找到考勤机
        Checker checker = checkerService.getByDevSno(devSno);
        log.info("考勤机============"+JSON.toJSONString(checker, true));

        if (checker == null){
            return TianBoApiResponse.emptySuccess("空设备，同步成功");
        }


        List<Children> children = childrenService.getByIds(personList,checker.getAreaId());
//        log.info("宝宝=========="+JSON.toJSONString(children, true));
        List<PersonInfo> infos = children.stream().map(o->{
            log.info("同步的Children id：" + o.getId()); // 新增此日志

            PersonInfo i = new PersonInfo();

            String sql = " SELECT * FROM  c_check_card WHERE userId in (:1) AND type =  1";

            List params = new ArrayList();
            params.add(o.getId());
            //所有卡号数据
            List<CheckCard> objectArrayList = baseNativeSqlRepository.sqlObjectList(sql, params, CheckCard.class);
            i.setSex(o.getGender());
            i.setPerson_name(o.getName());
            i.setPerson_id(o.getId());
            i.setId_card(o.getId());
            if (!StringUtils.isEmpty(o.getIdCard())) {
                if (o.getIdCard().equals("1685358611")){
                    i.setIc_card(o.getIdCard());
                }
            }
            if (!objectArrayList.isEmpty()){
                i.setIc_card(objectArrayList.get(0).getCardNo());
            }
            i.setTemplateImgUrl(Arrays.asList(o.getImgUrl()));
            i.setPerson_type("4");

            return i;
        }).collect(Collectors.toList());

        TianBoSyncPersonResponse response = new TianBoSyncPersonResponse();

        response.setMsg("同步成功");
        response.setPerson_list(infos);

        log.info("SYNC PERSON RESPONSE:::\n" +
                JSON.toJSONString(response, true));

        return response;
    }

}
